
import tool
import re
import os
import urllib2
from bs4 import BeautifulSoup
import log
class Single:
    def __init__(self, url = '', dir = '', tag = u'undefined', opener = None):
        self.opener = opener
        self.dir = dir
        self.tag = tag
        self.threads = []
        #print dir.decode('gbk').encode('utf8')
        self.tool = tool.Tool()
        self.log = log.Log()
        self.url = self.tool.removesomething('http://www.pixiv.net' + url)
        self.pid = re.search(re.compile('(\d+)', re.S), self.url)
        self.pid = self.pid.group(1)
        self.download_pic()

    def download_pic(self):
        try:
            soup = BeautifulSoup(self.opener.open(self.url), "html.parser")
            real_url = re.search(re.compile('.*?data-src="(.*?)"', re.S),
                             str(soup.find_all("img", class_="original-image")))
            real_url = real_url.group(1)
            p_type = self.tool.Pic_Type(real_url)
            save_dir = self.dir + '/pixiv_' + self.pid + '.' + p_type
            print save_dir
            if not os.path.exists(save_dir):
                file_pic = open(save_dir, 'wb')
                file_pic.write(self.download_request(real_url))
                file_pic.close()
            else:
                print 'The picture is exist, Skip Skip'
        except Exception, e:
            print e
            self.log.error_log(self.tag,self.pid, self.url)
    def download(self,real_url, save_dir):
        file_pic = open(save_dir, 'wb')
        file_pic.write(self.download_request(real_url))
        file_pic.close()

    def download_request(self,real_url):
        p_download_header = {
            'Accept-Language': 'zh-CN,zh;q=0.8',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0'
        }
        p_download_header['Referer'] = self.tool.removebig(self.url)
        download_request = urllib2.Request(url=real_url,
            headers=p_download_header)
        decode_url = self.opener.open(download_request)
        return decode_url.read()